// pages/order/courseSure/courseSure.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        goodsId: 0,
        type: '0',

        // 订单数据
        coupon_list: [],
        extract_shop: [],
        goods_list: [],
        intra_region: true,
        goods_total_price: "0.00",
        order_pay_price: "0.00",
        order_total_price: "0.00",
        point_total_price: "0.00",
        coupon_total_price: "0.00",
        user_points: "0",
        points_setting: null,
        point: {
            subtract_goodsTotalPrice: "0.00",
            usage_quantity: "0"
        },
        remark: '',
        usePointVal: '',

        // 是否选择优惠券
        chooseCoupon: null,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.data.goodsId = options.id;

        const type = options.type || '0';
        this.data.type = type;
        this.setData({
            type: type
        });

        this.loadGoodsDetail();

        wx.emitter.on('address.choose', this.chooseAddress)
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function(options) {
        wx.emitter.off('address.choose', this.chooseAddress)
    },

    // 用户选择地址
    chooseAddress: function(res) {
        this.setData({
            address: res
        });
    },

    // 选择优惠券
    chooseCouponChange: function(e) {
        this.groupSetData(() => {
            const chooseCoupon = e.detail;
            this.setData({
                chooseCoupon: chooseCoupon,
            });
            this.updateTotalAmount();
        });
    },

    // 选择使用积分
    usePointValInput: function(e) {
        let value = '';
        if (e.detail.value) {
            value = parseInt(e.detail.value);
            const max = parseInt(this.data.user_points);
            if (value > max) value = max;

            this.data.usePointVal = value;
            this.setData({
                usePointVal: value,
                chooseCoupon: null,
            });
        } else {
            this.data.usePointVal = '';
            this.setData({
                usePointVal: '',
                chooseCoupon: null,
            });
        }
        this.updateTotalAmount();

        return {
            value: value,
            cursor: value.length
        }
    },

    // 加载商品详情
    loadGoodsDetail: function() {
        return wx.http.get('api/curriculum.order/buyNow', {
            goods_id: this.data.goodsId,
            delivery: this.data.type === '0' ? 10 : 20,
            point: 0,
        }).then((res) => {
            this.groupSetData(() => {
                const data = res.data.data;
                data.point_max_amout = wx.BigNumber(data.order_pay_price)
                    .times(data.points_setting.discount.max_money_ratio)
                    .div(100)
                    .toFixed(2, wx.BigNumber.ROUND_DOWN);
                this.setData(data);
                this.updateTotalAmount();
            });
            return res.data.data;
        }, (err) => {
            console.warn("api/curriculum.order/buyNow", err)
        });
    },

    // 重新计算总价格
    updateTotalAmount: function() {
        // 商品金额
        let goodsTotalPrice = new wx.BigNumber('0.00');
        this.data.goods_list.forEach(it => {
            goodsTotalPrice = goodsTotalPrice.plus(it.total_price)
        });

        // 订单总金额
        let orderTotalPrice = goodsTotalPrice.plus('0.00');
        if (parseInt(this.data.delivery) === 10) {
            orderTotalPrice = orderTotalPrice.plus(this.data.express_price);
        }

        // 优惠券
        let couponTotalPrice = new wx.BigNumber('0.00');
        let chooseCoupon = this.data.chooseCoupon;
        if (chooseCoupon) {
            // 如果是折扣券
            if (chooseCoupon.coupon_type.value === 20) {
                couponTotalPrice = new wx.BigNumber(10);
                couponTotalPrice = couponTotalPrice.minus(chooseCoupon.discount).div(10).multipliedBy(orderTotalPrice);
            } else {
                couponTotalPrice = new wx.BigNumber(chooseCoupon.reduce_price);
            }
        }

        // 积分折扣金额
        let pointTotalPrice = new wx.BigNumber('0.00');
        const pointSetting = this.data.points_setting.discount;
        const comparedToFullOrderPrice = orderTotalPrice.comparedTo(pointSetting.full_order_price);
        if (this.data.points_setting.is_shopping_gift && (comparedToFullOrderPrice === 1 || comparedToFullOrderPrice === 0)) {
            pointTotalPrice = pointTotalPrice.plus(this.data.usePointVal || 0).times(pointSetting.discount_ratio);
            const comparedToMaxMoneyRatio = pointTotalPrice.comparedTo(pointSetting.max_money_ratio);
            if (comparedToMaxMoneyRatio === 1) {
                pointTotalPrice = new wx.BigNumber(pointSetting.max_money_ratio);
            }
            // pointTotalPrice = new wx.BigNumber(this.data.point.subtract_goodsTotalPrice);
        }

        // 实际支付金额
        let orderPayPrice = orderTotalPrice.minus(pointTotalPrice).minus(couponTotalPrice);
        if (orderPayPrice.comparedTo(0) === -1) {
            orderPayPrice = new wx.BigNumber("0.00");
        }

        this.setData({
            goods_total_price: goodsTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
            order_total_price: orderTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
            order_pay_price: orderPayPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
            point_total_price: pointTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
            coupon_total_price: couponTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
        });
    },

    // 是否开启积分兑换
    pointExchangeChange: function(e) {
        this.data.is_point_exchange = e.detail.value ? 1 : 0;
        this.updateTotalAmount();
    },

    // 跳转订单列表
    goOrder: function(orderId) {
        wx.redirectTo({
            url: `/pages/user/order/pay-success/pay-success?order_id=${orderId}&orderType=course`
        })
    },

    // 立即购买
    payTap: function() {
        if (this.data.goodsId) {
            this.goPay();
        } else {
            this.goPayCart();
        }
    },

    // 直接购买商品
    goPay: function() {
        const chooseCoupon = this.data.chooseCoupon;
        wx.http.post('api/curriculum.order/buyNow', {
            goods_id: this.data.goodsId,
            delivery: this.data.delivery,
            type: this.data.type,
            point: this.data.usePointVal,
            coupon_id: chooseCoupon ? chooseCoupon.user_coupon_id : 0,
            remark: this.data.remark
        }, {
            showLoading: true
        }).then((res) => {
            const payInfo = res.data.data.payment;
            const order_id = res.data.data.order_id;
            // if (this.data.goods_list[0].is_free.value === 10) {
            if (!payInfo) {
                this.goOrder(order_id);
            } else {
                wx.promise.requestPayment({
                    timeStamp: payInfo.timeStamp,
                    nonceStr: payInfo.nonceStr,
                    package: 'prepay_id=' + payInfo.prepay_id,
                    signType: 'MD5',
                    paySign: payInfo.paySign,
                }).then(() => {
                    this.goOrder();
                }, () => {
                    wx.showToast({
                        title: '支付失败',
                        icon: 'none',
                    });
                });
            }
        });
    },

});